#include "engine_impl.hh"
#include "thirdparty/kconfig/interface/config_factory.h"

namespace kratos { namespace engine {

extern EngineImpl* global_engine;

bool EngineImpl::startAsRoot() {
    if (run_) {
        return false;
    }
    if (!CommandOptionsRef.isDebug()) {
        loggerRef.selectAppender(corelib::AppenderType::Console);
    }
    try {
        config_ = ConfigFactory::createConfig();
        if (!config_) {
            logfatal << "ConfigFactory::createConfig() failure" << logend;
            return false;
        }
        config_->load("", CommandOptionsRef.getConfigFilePath());
        // parse config
        if (!parseConfig()) {
            return false;
        }
    } catch (std::exception& e) {
        logfatal << "Config file error:" << e.what() << corelib::logend;
        return false;
    }
    if (!startCore(true)) {
        return false;
    }
    if (!CommandOptionsRef.isDebug()) {
        global_engine = this;
        main_loop();
    }
    return true;
}

void EngineImpl::debug_loop(std::time_t now) {
    if (run_) {
        now_ = now;
        grid_->update(now_);
        http_->runOnce();
        processTimer();
        componentManager_.update();
        try {
            moduleManager_.onTick(now_);
        } catch (std::exception& e) {
            ENGINE_LOG_EXCEPTION(e, "moduleManager_.onTick, timestamp:", now_);
        }
    }
}

}}
